﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Shared.Models.Trade;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using log4net;
using WatsonWebsocket;
using WebSocketSharp.Server;
using System.Net;
using PlaceOrder_Core.QuanYi;
using PlaceOrder_Core.Services.Interfaces;
using System.Net.WebSockets;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Shared.ModelsToLily;
using PlaceOrder_Shared.Models.QaingPing;
using System.ComponentModel.DataAnnotations;
using static PlaceOrder_Core.Models.QuanYi.QuanYiServerBaseClass;

namespace PlaceOrder_Core.Helper
{
    /// <summary>
    /// 服务端WebSocket帮助类
    /// </summary>
    public class ServerWebSocketHelper : IDisposable
    {
        private static string serverUri = $"{DataHelper.BaseConfig.WebSocketUrl}/websocket/{UserHelper.Token}";

        public WatsonWsServer serverWebSocket; //服务端websocket
        public WatsonWsServer serverAdminSocket; //服务端websocket
        private OrderServer orderServer;

        public List<QuanYiServerConnectionClass> ClientConnections = new List<QuanYiServerConnectionClass>();
        public List<Guid> AdminConnections = new List<Guid>();

        private bool isDisposed = false;
        public void Dispose()
        {
            isDisposed = true;

            if (serverWebSocket != null)
            {
                serverWebSocket.Dispose();
            }

            if(serverAdminSocket!=null)
            {
                serverAdminSocket.Dispose();
            }
        }
        private readonly IDailyData _dailyData;
        public static Dictionary<int, string> UserInfo = new Dictionary<int, string>();
        public ServerWebSocketHelper(IDailyData dailyData)
        {
            _dailyData=dailyData;
            //var users= _dailyData.GetAllUsers();
            //foreach (var user in users)
            //{
            //    UserInfo[user.UserID] = user.NickName;
            //}
        }
        private Thread WebSocketserverThread;//服务端端线程
        private Thread MainSocket;//主线程
        private Thread WatchDogThread;//心跳线程
        private Thread SendMessageThread;//获取数据线程

        #region 对接客户端的 服务端，监听在38888端口
        /// <summary>
        /// 发送消息至客户端
        /// </summary>
        /// <param name="qsr"></param>
        public void SendMessageToClients(QuanYiOrderServerResponseClass qsr)
        {
            try
            {
                string msg = JsonConvert.SerializeObject(qsr);

                switch (qsr.DataType)
                {
                    case QuanYiServerBaseClass.DataTypeEnum.Login:

                    case QuanYiServerBaseClass.DataTypeEnum.Order:

                    case QuanYiServerBaseClass.DataTypeEnum.RequestReview:
                    case QuanYiServerBaseClass.DataTypeEnum.NewChatMessageIn:

                        //serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        var tempConnections = ClientConnections.Where(o=>o.IsIndex==true).Select(o => o.SessionID).Distinct().ToList();
                        lock (connectionAdminLock)
                        {
                            
                            foreach (var clientGuid in tempConnections)
                            {
                                serverWebSocket.SendAsync(clientGuid, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                            }
                        }
                        //AppLog.WriteInfo("发送消息至admin" + msg);
                        break;

                    case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:
                        if (qsr.UserID != 0)
                        {
                            serverWebSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        }
                        else
                        {
                            lock (connectionAdminLock)
                            {
                                foreach (var adminGuid in AdminConnections)
                                {
                                    //serverWebSocket.SendAsync(adminGuid, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                                }
                            }
                        }
                        break;

                    default:
                        serverWebSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        break;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "SendReponse:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
            }
        }


        /// <summary>
        /// lxw服务端发送给客户端
        /// </summary>
        /// <param name="order"></param>
        public void SendQiangPingMessageToClients(string  message)
        {
            try
            {
                // 解析 JSON 消息
                JObject jsonMessage = JObject.Parse(message);
                int userId = jsonMessage["data"]?["userId"]?.ToObject<int>() ?? 0;

                var userConnection = ClientConnections.Where(o => o.UserID == userId).FirstOrDefault();
                if(userConnection==null)
                {
                    return;
                }
                var clientGuid = userConnection.SessionID;
                lock (connectionAdminLock)
                {
                   serverWebSocket.SendAsync(clientGuid, message, System.Net.WebSockets.WebSocketMessageType.Text);
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "SendQiangPingMessageToClients" + "服务端发送强平消息到客户端:" + message, ex.StackTrace);
            }
        }
        /// <summary>
        /// 服务端的服务方法(lxw-38888)
        /// </summary>
        public void serverWebSocketStart()
        {
            try
            {
                serverWebSocket = new WatsonWsServer("*", 38888);
                serverWebSocket.ClientConnected -= OrderServer_ClientConnected;
                serverWebSocket.ClientDisconnected -= OrderServer_ClientDisconnected;
                serverWebSocket.MessageReceived -= OrderServer_MessageReceived;

                serverWebSocket.ClientConnected += OrderServer_ClientConnected;
                serverWebSocket.ClientDisconnected += OrderServer_ClientDisconnected;
                serverWebSocket.MessageReceived += OrderServer_MessageReceived;
                
                serverWebSocket.Start();
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "serverWebSocketStart" + ex.StackTrace);
            }

        }


        private void OrderServer_ClientConnected(object? sender, ConnectionEventArgs e)
        {
            try
            {
                QuanYiServerConnectionClass qcc = new QuanYiServerConnectionClass();
                qcc.SessionID = e.Client.Guid;

            
             
                    if (!ClientConnections.Any(x => x.SessionID == qcc.SessionID))
                    {
                        ClientConnections.Add(qcc);
                        AppLog.WriteError($"有新用户连接,SessionId={qcc.SessionID},当前总连接数：{ClientConnections.Count()}");

                     }

            }
            catch(Exception ex)
            {
                AppLog.WriteError("OrderServer_ClientConnected异常" + ex.StackTrace + ex.Message);
            }

        }
        private readonly object _lockObject = new object(); // 锁对象


        private void OrderServer_MessageReceived(object? sender, MessageReceivedEventArgs e)
        {
            string msg = Encoding.UTF8.GetString(e.Data);
            //Debug.WriteLine(msg);
            //return;
            QuanYiOrderServerResponseClass qsr = null;
            try
            {
                qsr = JsonConvert.DeserializeObject<QuanYiOrderServerResponseClass>(msg);
            }
            catch
            {
                AppLog.WriteError($"解析qsr失败{qsr?.ToString()}");
                return;
            }
            if (qsr == null)
            {
                return;
            }
            qsr.SessionID = e.Client.Guid;
            //if (!VerifyToken(qsr.Token))
            //{
            //    qsr.Code = 1;
            //    qsr.Message = "登录已过期，请重新登录";
            //    qsr.DataType = QuanYiOrderServerResponseClass.DataTypeEnum.Login;
            //    qsr.Trade = null;
            //    serverWebSocket.SendAsync(e.Client.Guid, JsonConvert.SerializeObject(qsr), System.Net.WebSockets.WebSocketMessageType.Text).Wait();
            //    serverWebSocket.DisconnectClient(e.Client.Guid);
            //    AppLog.WriteError("登录已过期，请重新登录");
            //    return;
            //}

            if (qsr.DataType == QuanYiOrderServerResponseClass.DataTypeEnum.Login)
            {
                lock (_lockObject)
                {
                    // ClientConnections 是共享资源，确保线程安全
                    var qcc = ClientConnections.SingleOrDefault(x => x.SessionID == e.Client.Guid);
                    if (qcc == null)
                    {
                        return;
                    }
                    if (qsr.IsIndex == false)
                    {
                        ClientConnections.RemoveAll(x => x.SessionID == e.Client.Guid);
                        AppLog.WriteError($"连接 {e.Client.Guid} 被移除，因为 IsIndex 为 false,非OrderListViewmodel的连接");
                    }
                
                 
                    qcc.IsIndex = qsr.IsIndex;
                    qcc.UserID = qsr.UserID;
                    qcc.Token = qsr.Token;
                   

                    AppLog.WriteError($"新用户连接UserID是{qcc.UserID},SessionId是{qcc.SessionID}" );
                    AppLog.WriteError("当前websocket连接数为"+ ClientConnections.Count());

                }
            }
            qsr.RemoteIP = e.Client.Ip;
            if (qsr.DataType == QuanYiServerBaseClass.DataTypeEnum.ChatMessage)
            {

            }
            else
            {
                //_dailyData.TradeSimLog(qsr);
            }

            if (QuanYiOrderServerMessageEvent != null)
            {
                QuanYiOrderServerMessageEvent(qsr);
            }
        }
        //private void OrderServer_MessageReceived(object? sender, MessageReceivedEventArgs e)
        //{
        //    string msg = Encoding.UTF8.GetString(e.Data);
        //    //Debug.WriteLine(msg);
        //    //return;
        //    QuanYiOrderServerResponseClass qsr = null;
        //    try
        //    {
        //        qsr = JsonConvert.DeserializeObject<QuanYiOrderServerResponseClass>(msg);
        //    }
        //    catch
        //    {
        //        AppLog.WriteError($"解析qsr失败{qsr.ToString()}");
        //        return;
        //    }
        //    if (qsr == null)
        //    {
        //        return;
        //    }
        //    qsr.SessionID = e.Client.Guid;
        //    //if (!VerifyToken(qsr.Token))
        //    //{
        //    //    qsr.Code = 1;
        //    //    qsr.Message = "登录已过期，请重新登录";
        //    //    qsr.DataType = QuanYiOrderServerResponseClass.DataTypeEnum.Login;
        //    //    qsr.Trade = null;
        //    //    serverWebSocket.SendAsync(e.Client.Guid, JsonConvert.SerializeObject(qsr), System.Net.WebSockets.WebSocketMessageType.Text).Wait();
        //    //    serverWebSocket.DisconnectClient(e.Client.Guid);
        //    //    AppLog.WriteError("登录已过期，请重新登录");
        //    //    return;
        //    //}

        //    if (qsr.DataType == QuanYiOrderServerResponseClass.DataTypeEnum.Login)
        //    {
        //        //ClientConnections.RemoveAll(x => x.UserID == qsr.UserID);
        //        var qcc = ClientConnections.SingleOrDefault(x => x.SessionID == e.Client.Guid);
        //        if (qcc == null)
        //        {
        //            qcc = new QuanYiServerConnectionClass();
        //            qcc.SessionID = e.Client.Guid;
        //            qcc.UserID = qsr.UserID;
        //            qcc.IsIndex = qsr.IsIndex;
        //            ClientConnections.Add(qcc);
        //        }
        //        qcc.IsIndex = qsr.IsIndex;
        //        qcc.UserID = qsr.UserID;
        //        qcc.Token = qsr.Token;
        //    }
        //    qsr.RemoteIP = e.Client.Ip;
        //    if(qsr.DataType== QuanYiServerBaseClass.DataTypeEnum.ChatMessage)
        //    {

        //    }else
        //    {
        //        //_dailyData.TradeSimLog(qsr);
        //    }

        //        if (QuanYiOrderServerMessageEvent != null)
        //        {
        //            QuanYiOrderServerMessageEvent(qsr);
        //        }


        //}

        #region 服务端socket连接相关
        private readonly object _clientConnectionsLock = new object();
        private void OrderServer_ClientDisconnected(object? sender, DisconnectionEventArgs e)
        {
            try
            {
                AppLog.WriteError("有客户端断连了 SessionID: " + e.Client.Guid);
                lock (_clientConnectionsLock) // 加锁，确保线程安全
                {
                    // 查找匹配的客户端连接
                    var matchingConnections = ClientConnections
                        .Where(x => x.SessionID == e.Client.Guid)
                        .ToList();

                    if (matchingConnections.Count > 1)
                    {
                        AppLog.WriteError("SessionID重复: " + e.Client.Guid);
                    }

                    // 获取匹配的第一个客户端连接
                    var clientConnection = matchingConnections.FirstOrDefault();
                    if (clientConnection != null)
                    {
                        AppLog.WriteError($"移除OrderlistViewModel的连接:SessionId:{e.Client.Guid},UserId:{clientConnection.UserID},IsIndex:{clientConnection.IsIndex},连接总数为：{ClientConnections.Count()}");
                       
                      
                        int userId = clientConnection.UserID;
                        ClientConnections.RemoveAll(x => x.SessionID == e.Client.Guid);

                        // 检查是否没有更多此用户的连接
                        if (!ClientConnections.Any(x => x.UserID == userId))
                        {
                            var qsr = new QuanYiOrderServerResponseClass
                            {
                                UserID = userId,
                                DataType = DataTypeEnum.Logout
                            };
                            QuanYiOrderServerMessageEvent(qsr);
                        }
                    }
                    else
                    {
                        AppLog.WriteError("没有找到与SessionID匹配的连接: " + e.Client.Guid);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("OrderServer_ClientDisconnected异常: " + ex.StackTrace + " " + ex.Message);
            }
        }

        //private void OrderServer_ClientDisconnected(object? sender, DisconnectionEventArgs e)
        //{
        //    QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
        //    try
        //    {
        //        AppLog.WriteError("有客户端断连了 " + qsr.UserID);

        //        lock (_clientConnectionsLock) // 加锁，确保线程安全
        //        {
        //            // 查找匹配的客户端连接
        //            var matchingConnections = ClientConnections
        //                .Where(x => x.SessionID == e.Client.Guid)
        //                .ToList();

        //            if (matchingConnections.Count > 1)
        //            {
        //                AppLog.WriteError("SessionID重复");
        //            }

        //            // 获取匹配的第一个客户端连接
        //            var clientConnection = matchingConnections.FirstOrDefault();
        //            if (clientConnection != null)
        //            {
        //                int UserID = clientConnection.UserID;
        //                ClientConnections.RemoveAll(x => x.SessionID == e.Client.Guid);

        //                // 检查是否没有更多此用户的连接
        //                if (ClientConnections.Count(x => x.UserID == UserID) == 0)
        //                {
        //                    qsr.UserID = UserID;
        //                    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.Logout;
        //                    QuanYiOrderServerMessageEvent(qsr);
        //                }
        //            }
        //            else
        //            {
        //                AppLog.WriteError("没有connection");
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError("OrderServer_ClientDisconnected异常: " + ex.StackTrace + " " + ex.Message);
        //    }
        //}
        //private void OrderServer_ClientDisconnected(object? sender, DisconnectionEventArgs e)
        //{
        //    QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
        //    try
        //    {
        //        AppLog.WriteError("有客户端断连了 " + qsr.UserID);

        //        Find the client connection matching the session ID
        //        var matchingConnections = ClientConnections.Where(x => x.SessionID == e.Client.Guid).ToList();

        //        if (matchingConnections.Count > 1)
        //        {
        //            AppLog.WriteError("Warning: Multiple connections found for the same session ID.");
        //        }

        //        Get the UserID from the first match(if any)
        //            var clientConnection = matchingConnections.FirstOrDefault();
        //        if (clientConnection != null)
        //        {
        //            int UserID = clientConnection.UserID;
        //            ClientConnections.RemoveAll(x => x.SessionID == e.Client.Guid);

        //            Check if there are no more connections for this UserID
        //            if (ClientConnections.Count(x => x.UserID == UserID) == 0)
        //                {
        //                    qsr.UserID = UserID;
        //                    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.Logout;
        //                    QuanYiOrderServerMessageEvent(qsr);
        //                }
        //        }
        //        else
        //        {
        //            AppLog.WriteError("No client connection found for the session ID.");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError("OrderServer_ClientDisconnected异常: " + ex.StackTrace + " " + ex.Message);
        //    }

        //}



        public void SendResponseToClient(QuanYiOrderServerResponseClass qsr)
        {
            try
            {
                string msg = JsonConvert.SerializeObject(qsr);
                switch (qsr.DataType)
                {
                    case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:
                        if (qsr.UserID != 0)
                        {
                            serverWebSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        }
                        else
                        {
                            foreach (var s in ClientConnections)
                            {
                                serverWebSocket.SendAsync(s.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                            }
                        }

                        break;
               
                    case QuanYiServerBaseClass.DataTypeEnum.QTradeNotOpen:
                        if(ClientConnections==null||ClientConnections.Count==0)
                        {
                            AppLog.WriteInfo("未找到连接的客户端");
                            break;
                        }
                        foreach(var item in ClientConnections)
                        {
                            serverWebSocket.SendAsync(item.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);

                        }
                        
                        AppLog.WriteInfo($"发送Qtrade未开启消息至所有连接的客户端,数量：{ClientConnections.Count()}");
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.Order:
                    default:
                        serverWebSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        break;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "SendReponse:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
            }
        }



       


        public static List<BidHistory> GetBidHistories(string TsCode)
        {
            List<BidHistory> tmpBids = new List<BidHistory>();
            try
            {
                string tmp = "";
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
                    client.Timeout = new TimeSpan(0, 0, 3);
                    client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");
                    HttpResponseMessage res = client.GetAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=0")).Result;
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = res.Content.ReadAsStringAsync().Result;
                    }
                }
                JObject o = JObject.Parse(tmp);
                tmpBids = JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString());

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
                    client.Timeout = new TimeSpan(0, 0, 3);
                    client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");
                    HttpResponseMessage res = client.GetAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=1")).Result;
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = res.Content.ReadAsStringAsync().Result;
                    }
                }
                o = JObject.Parse(tmp);
                tmpBids.AddRange(JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString()));
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "WebSockerHepler" + "GetBidHistories" + ex.StackTrace);
            }
            return tmpBids.Where(x => x.Forward == false).ToList();
        }

        public string GetUserToken(int UserID)
        {
            return ClientConnections.First(x => x.UserID == UserID).Token;
        }


        public delegate void QuanYiServerMessageEventHandle(QuanYiServerResponseClass QSR);
        public event QuanYiServerMessageEventHandle QuanYiServerMessageEvent;
        #endregion
        #endregion


        #region 对接管理端的 服务端，监听在38889端口
        private readonly object connectionAdminLock = new object();
        /// <summary>
        /// 管理端的服务方法
        /// </summary>
        public void adminWebSocketStart()
        {
            try
            {
                serverAdminSocket = new WatsonWsServer("*", 38889);
                serverAdminSocket.ClientConnected += OrderAdmin_Connected;
                serverAdminSocket.ClientDisconnected += OrderAdmin_DisConnected;
                serverAdminSocket.MessageReceived += OrderAdmin_MessageReceived;
                serverAdminSocket.Start();
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "adminWebSocketStart" + ex.StackTrace);
            }

        }

        private void OrderAdmin_DisConnected(object? sender, DisconnectionEventArgs e)
        {
            if (e?.Client?.Guid != null)
            {
                AppLog.WriteInfo($"有管理端人员断开连接：ip地址：{e.Client.Ip},端口号：{e.Client.Port},GUID:{e.Client.Guid}");
                lock (connectionAdminLock)
                {
                    this.AdminConnections.Remove(e.Client.Guid);
                }
            }
        }

        private void OrderAdmin_Connected(object? sender, ConnectionEventArgs e)
        {
            string msg = $"有管理端人员连接成功：ip地址：{e.Client.Ip},端口号：{e.Client.Port},GUID:{e.Client.Guid}";
            AppLog.WriteInfo(msg);
            if (e?.Client?.Guid != null)
            {
                lock (connectionAdminLock)
                {
                    //this.AdminGuid = e.Client.Guid;
                    this.AdminConnections.Add(e.Client.Guid);
                    AdminMessageEvent(msg);
                }
            }
        }

        /// <summary>
        /// 服务端接收管理端发来的消息,全发string就行,管理端其实不会往服务端发东西
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrderAdmin_MessageReceived(object? sender, MessageReceivedEventArgs e)
        {
            string msg = Encoding.UTF8.GetString(e.Data);
            //Debug.WriteLine(msg);
            //return;
            QuanYiOrderServerResponseClass qsr = null;
            try
            {
                qsr = JsonConvert.DeserializeObject<QuanYiOrderServerResponseClass>(msg);
            }
            catch
            {
                AppLog.WriteError($"解析qsr失败{qsr.ToString()}");
                return;
            }
            if (qsr == null)
            {
                return;
            }
            qsr.SessionID = e.Client.Guid;
            if (!VerifyToken(qsr.Token))
            {
                qsr.Code = 1;
                qsr.Message = "登录已过期，请重新登录";
                qsr.DataType = QuanYiOrderServerResponseClass.DataTypeEnum.Login;
                qsr.Trade = null;
                serverWebSocket.SendAsync(e.Client.Guid, JsonConvert.SerializeObject(qsr), System.Net.WebSockets.WebSocketMessageType.Text).Wait();
                serverWebSocket.DisconnectClient(e.Client.Guid);
                AppLog.WriteError("登录已过期，请重新登录");
                return;
            }

            if (qsr.DataType == QuanYiOrderServerResponseClass.DataTypeEnum.Login)
            {
                //ClientConnections.RemoveAll(x => x.UserID == qsr.UserID);
                var qcc = ClientConnections.SingleOrDefault(x => x.SessionID == e.Client.Guid);
                if (qcc == null)
                {
                    qcc = new QuanYiServerConnectionClass();
                    qcc.SessionID = e.Client.Guid;
                    qcc.UserID = qsr.UserID;
                    qcc.IsIndex = qsr.IsIndex;
                    ClientConnections.Add(qcc);
                }
                qcc.IsIndex = qsr.IsIndex;
                qcc.UserID = qsr.UserID;
                qcc.Token = qsr.Token;
            }
            qsr.RemoteIP = e.Client.Ip;
            //_dailyData.TradeSimLog(qsr);
            if (QuanYiOrderServerMessageEvent != null)
            {
                QuanYiOrderServerMessageEvent(qsr);
            }


        }

        // public void SendMessageToAdmins(QuanYiOrderServerResponseClass qsr)
        //{
        //    try
        //    {
        //        string msg = JsonConvert.SerializeObject(qsr);
        //        switch (qsr.DataType)
        //        {
        //            case QuanYiServerBaseClass.DataTypeEnum.Login:
        //                serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
        //                break;

        //            case QuanYiServerBaseClass.DataTypeEnum.Order:
        //                serverAdminSocket.SendAsync(AdminGuid, msg, System.Net.WebSockets.WebSocketMessageType.Text);

        //                break;
        //            case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:
        //                if (qsr.UserID != 0)
        //                {
        //                    serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
        //                }
        //                else
        //                {
        //                    foreach (var s in ClientConnections)
        //                    {
        //                        serverAdminSocket.SendAsync(s.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
        //                    }
        //                }

        //                break;
        //            default:
        //                serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
        //                break;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "SendReponse:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
        //    }
        //}


        /// <summary>
        /// 发送消息至管理端
        /// </summary>
        /// <param name="qsr"></param>
        public void SendMessageToAdmins(QuanYiOrderServerResponseClass qsr)
        {
            try
            {
                string msg = JsonConvert.SerializeObject(qsr);

                switch (qsr.DataType)
                {
                    case QuanYiServerBaseClass.DataTypeEnum.Login:

                    case QuanYiServerBaseClass.DataTypeEnum.Order:

                    case QuanYiServerBaseClass.DataTypeEnum.RequestReview:
                    case QuanYiServerBaseClass.DataTypeEnum.NewChatMessageIn:

                        //serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        lock (connectionAdminLock)
                        {
                            foreach (var adminGuid in AdminConnections)
                            {
                                serverAdminSocket.SendAsync(adminGuid, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                            }
                        }
                        //AppLog.WriteInfo("发送消息至admin" + msg);
                        break;

                    case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:
                        if (qsr.UserID != 0)
                        {
                            serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        }
                        else
                        {
                            lock (connectionAdminLock)
                            {
                                foreach (var adminGuid in AdminConnections)
                                {
                                    serverAdminSocket.SendAsync(adminGuid, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                                }
                            }
                        }
                        break;

                    default:
                        serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        break;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "SendReponse:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
            }
        }



        /// <summary>
        /// 回复admin
        /// </summary>
        /// <param name="qsr"></param>
        public void SendResponseToAdmin(QuanYiOrderServerResponseClass qsr)
        {
            try
            {
                string msg = JsonConvert.SerializeObject(qsr);
                switch (qsr.DataType)
                {
                    case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:
                        if (qsr.UserID != 0)
                        {
                            serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        }
                        else
                        {
                            foreach (var s in ClientConnections)
                            {
                                serverAdminSocket.SendAsync(s.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                            }
                        }

                        break;
                    default:
                        serverAdminSocket.SendAsync(qsr.SessionID, msg, System.Net.WebSockets.WebSocketMessageType.Text);
                        break;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "SendReponse:" + JsonConvert.SerializeObject(qsr), ex.StackTrace);
            }
        }
        public void SendMessageToAdmin(string msg)
        {
            serverAdminSocket.SendAsync(AdminConnections[0], msg);
        }
        #endregion




        #region 通用方法
        private bool SubscribeTradeSucceeded = false; //订阅交易信息

        private static JsonSerializerSettings settings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            MissingMemberHandling = MissingMemberHandling.Ignore
        };

        public bool VerifyToken(string Token)
        {
            try
            {
                HttpWebRequest request;
                HttpWebResponse response;
                StreamReader myStreamReader;
                string tmp;
                request = (HttpWebRequest)WebRequest.Create($"{DataHelper.BaseConfig.HttpUrl}/api/verifyToken");
                request.Method = "Post";
                request.Accept = "application/json";
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36";
                request.ContentType = "application/json; charset=utf-8";
                request.ProtocolVersion = HttpVersion.Version10;
                request.Timeout = 3000;
                var postData = Encoding.UTF8.GetBytes("{\"token\":\"" + Token + "\"}");
                request.ContentLength = postData.Length;
                request.KeepAlive = true;
                var postStream = request.GetRequestStream();
                postStream.Write(postData, 0, postData.Length);
                postStream.Close();

                response = (HttpWebResponse)request.GetResponse();
                myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                tmp = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    AppLog.WriteError(response.StatusDescription + " " + tmp+"Worker"+"PushBids"+"");
                    return false;
                }
                JObject o = JObject.Parse(tmp);
                if (o["code"].ToString() != "00000")
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "ServerWebSocketHelper" + "VerifyToken" + ex.StackTrace);
                return false;
            }
            return true;
        }

        #endregion

        #region 委托
        public delegate void QuanYiOrderServerMessageEventHandle(QuanYiOrderServerResponseClass QSR);

        public event QuanYiOrderServerMessageEventHandle QuanYiOrderServerMessageEvent;


        public delegate void AdminMessageEventHandle(string message);

        public event AdminMessageEventHandle AdminMessageEvent;

        public delegate void ServerDisconnectedEventHandle();
        public event ServerDisconnectedEventHandle ServerDisconnectedEvent;

        public delegate void ServerConnectedEventHandle();
        public event ServerConnectedEventHandle ServerConnectedEvent;

        public delegate void QuanYiOrderClientMessageEventHandle(QuanYiOrderServerResponseClass QSR);
        public static event QuanYiOrderClientMessageEventHandle QuanYiOrderClientMessageEvent;

        public delegate void SubscribeLilyTradeEventHandle(LilyTradeModel Trade);
        public  event SubscribeLilyTradeEventHandle SubscribeLilyTradeEvent;
        #endregion
    }
}
